package com.lzq.hander;

import com.lzq.model.ApiErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * @author 2019/1/30 16:24 by 刘赵强
 * 统一异常处理
 **/
@RestControllerAdvice
@Slf4j
public class CommonExceptionHandler {
    @ExceptionHandler(value = {ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiErrorResponse constraintViolationException(ConstraintViolationException ex) {
        StringBuilder sb = new StringBuilder();
        for (ConstraintViolation violation : ex.getConstraintViolations()) {
            sb.append(violation.getMessage());
        }
        log.error(ex.getMessage(),ex);
        return new ApiErrorResponse(500, 5001, sb.toString());
    }

    @ExceptionHandler(value = {IllegalArgumentException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiErrorResponse IllegalArgumentException(IllegalArgumentException ex) {
        log.error(ex.getMessage(),ex);
        return new ApiErrorResponse(501, 5002, ex.getMessage());
    }

    @ExceptionHandler(value = {NoHandlerFoundException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ApiErrorResponse noHandlerFoundException(Exception ex) {
        log.error(ex.getMessage(),ex);
        return new ApiErrorResponse(404, 4041, ex.getMessage());
    }


    @ExceptionHandler(value = {Exception.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiErrorResponse unknownException(Exception ex) {
        log.error(ex.getMessage(),ex);
        return new ApiErrorResponse(500, 5002, ex.getMessage());
    }
}

